package com.elangzhi.ssm.modules.orderFrom.app;

import com.alibaba.fastjson.JSONObject;
import com.elangzhi.ssm.controller.json.Tip;
import com.elangzhi.ssm.model.*;
import com.elangzhi.ssm.modules.goods.services.GoodsService;
import com.elangzhi.ssm.modules.orderFrom.services.OrderFromService;
import com.elangzhi.ssm.modules.orderGoods.services.OrderGoodsService;
import com.elangzhi.ssm.modules.receiptAddress.services.ReceiptAddressService;
import com.elangzhi.ssm.modules.shop.services.ShopService;
import com.elangzhi.ssm.modules.shopEvent.services.ShopEventService;
import com.elangzhi.ssm.modules.user.services.ThinksService;
import com.elangzhi.ssm.modules.user.services.UserService;
import com.elangzhi.ssm.tools.UUIDFactory;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
* 订单 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/orderFrom")
public class AppOrderFromController {

    /**
     * 根据订单号获取订单详情
     * @param id 订单号 id
     * @return 订单详情
     */
    @RequestMapping("/findById")
    @ResponseBody
    public OrderFrom findById( @RequestParam Long id){
        OrderFrom orderFrom = orderFromService.selectById(id);
        if(orderFrom != null){
            List<OrderGoods> goodses = orderGoodsService.listByOrderFromId(orderFrom.getId());
            orderFrom.setGoodses(goodses);

            orderFrom.setAddress(receiptAddressService.selectById(orderFrom.getReceiptAddressId()));
        }
        return orderFrom;
    }

    /**
     * 根据用户Id获取用户订单列表
     * @param userId 用户id
     * @param page 第几页
     * @param size 每页大小
     * @return 订单列表，带分页
     */
    @RequestMapping("/listByUserId")
    @ResponseBody
    public PageInfo<OrderFrom> listByUserId(
            @RequestParam Long userId,
            @RequestParam Integer page,
            @RequestParam Integer size
            ){
        PageInfo<OrderFrom> pageInfo = orderFromService.listByUserId(userId,page,size);
        List<OrderFrom> froms = pageInfo.getList();
        for(OrderFrom orderFrom : froms){
            List<OrderGoods> goodses = orderGoodsService.listByOrderFromId(orderFrom.getId());
            orderFrom.setGoodses(goodses);
        }
        pageInfo.setList(froms);
        return pageInfo;
    }

    /**
     * 提交订单 必选参数如下：
     * userId 用户id
     * shopId 店铺id
     * sendType //配送类型
     * receiptAddressId  //收货地址
     * intro 简介
     * goodsList 所购商品字符串
     * @param orderFrom 参数实体
     * @return 成功状态
     */
    @RequestMapping("/submit")
    @ResponseBody
    public Tip submit(OrderFrom orderFrom){

        try {
            // 生成订单id
            orderFrom.setId(UUIDFactory.getLongId());
            // 设置订单下单时间
            Date date = new Date();
            orderFrom.setSetTime(date);
            orderFrom.setPayTime(date);
            orderFrom.setSendTime(date);
            // 设置类型1，商品订单
            orderFrom.setType(1);
            // 订单状态1，已提交，等待付款
            orderFrom.setStatus(1);
            // 保存商品列表 且返回并计算总价
            BigDecimal sum = insertGoods(orderFrom.getId(),orderFrom.getGoodsList());
            orderFrom.setPrice(sum);
            // 保存订单
            orderFromService.insert(orderFrom);
            return new Tip(orderFrom.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 保存订单商品列表
     * @param id 订单id
     * @param goodsList 订单商品列表字符串
     * @return 订单总价
     * @throws Exception 保存订单商品失败
     */
    private BigDecimal insertGoods(Long id,String goodsList) throws Exception {
        //记录总价
        BigDecimal sum = new BigDecimal("0.0");
        //保存商品列表
        for(String goodsParam : goodsList.split(";")){
            Long goodsId = Long.valueOf(goodsParam.split(":")[0]);
            Integer number = Integer.valueOf(goodsParam.split(":")[1]);

            // 设置基本信息
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setId(UUIDFactory.getLongId());
            orderGoods.setOrderFromId(id);
            orderGoods.setType(1);
            orderGoods.setInfoId(goodsId);
            orderGoods.setNumber(number);

            // 获取商品价格和名称
            Goods goodsValue = goodsService.selectById(orderGoods.getInfoId());
            orderGoods.setName(goodsValue.getName());
            BigDecimal price = calculationPrice(goodsValue,number);
            orderGoods.setPrice(price);
            orderGoodsService.insert(orderGoods);
            // 计入总价
            sum = sum.add(price);
        }
        return sum;
    }

    /**
     * 计算总价
     * @param goodsValue 商品信息
     * @param number 商品
     * @return 总价
     */
    private BigDecimal calculationPrice(Goods goodsValue,Integer number){
        // 获取单价
        BigDecimal unit = goodsValue.getPrice();
        // 获取数量
        BigDecimal count = new BigDecimal(number);
        // 获取活动列表
        List<ShopEvent> events = shopEventService.listByGoodsId(goodsValue.getId());
        // 获取活动单价
        for(ShopEvent shopEvent : events){
            // 限时打折
            if(shopEvent.getType() == 1){
                Double v1 = new Double(shopEvent.getZheValue());
                Double v2 = new Double(100);
                BigDecimal zheValue = new BigDecimal(new Double(v1/v2).toString());
                unit = unit.multiply(zheValue);
            }
        }
        // 获取总价
        return unit.multiply(count);
    }

    /**
     * 支付订单
     * @param id 订单id
     * @param thinksId 账号
     * @return 支付状态
     */
    @RequestMapping("/pay")
    @ResponseBody
    public Tip pay(Long id,String thinksId){
        OrderFrom of = orderFromService.selectById(id);
        try {

            // 订单超时
            if(of.getStatus() != 1){
                return new Tip(2);
            }

            JSONObject jsonObject ;

            if(of.getShopId().equals(888888l)){
                jsonObject = thinksService.xiaofei(thinksId,of.getPrice().toString());
            }else{
                jsonObject = thinksService.zhuanzhang(thinksId,"888888",of.getPrice().toString());
            }

            if(jsonObject.getBoolean("state")){
                of.setStatus(2);
                of.setPayTime(new Date());
                of.setPayInfo(thinksId);
                of.setPayType("星客思支付");
                orderFromService.updateById(of);
                return new Tip(jsonObject);
            }else{
                return new Tip(3,jsonObject);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }

    }

    /**
     * 发货 必选参数如下：
     * id 订单id
     * sendType 配送方中文名，如果配送，就写配送，如果快递，就写顺丰快递之类的，自提就写自提
     * sendInfo 快递单号，配送单号等
     * @param orderFrom 实体参数
     * @return 操作状态
     */
    @RequestMapping("/send")
    @ResponseBody
    public Tip send(OrderFrom orderFrom){
        try {
            OrderFrom of ;
            of = orderFromService.selectById(orderFrom.getId());
            of.setStatus(3);
            of.setSendTime(new Date());
            of.setSendType(orderFrom.getSendType());
            of.setSendInfo(orderFrom.getSendInfo());
            orderFromService.updateById(of);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }

    }

    /**
     * 完成订单 必选参数如下：
     * id 订单id
     * @param id 订单id
     * @return 操作状态
     */
    @RequestMapping("/finish")
    @ResponseBody
    public Tip finish(Long id){
        try {
            OrderFrom of = orderFromService.selectById(id);

            JSONObject jsonObject;
            if(!of.getShopId().equals(888888l)){
                Shop shop = shopService.selectById(of.getShopId());
                User user = userService.selectById(shop.getUserId());
                jsonObject = thinksService.zhuanzhang("888888",user.getThinksId(),of.getPrice().toString());
                if(!jsonObject.getBoolean("state")){
                    return new Tip(2);
                }
            }
            of.setStatus(4);
            orderFromService.updateById(of);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 评价完成 必选参数如下：
     * id 订单id
     * @param orderFrom 实体参数
     * @return 操作状态
     */
    @RequestMapping("/comment")
    @ResponseBody
    public Tip comment(OrderFrom orderFrom){
        try {
            OrderFrom of ;
            of = orderFromService.selectById(orderFrom.getId());
            of.setStatus(5);
            orderFromService.updateById(of);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }

    /**
     * 取消订单 必选参数如下：
     * id 订单id
     * @param orderFrom 实体参数 {id}
     * @return 操作状态
     */
    @RequestMapping("/cancel")
    @ResponseBody
    public Tip cancel(OrderFrom orderFrom){
        try {
            OrderFrom of ;
            of = orderFromService.selectById(orderFrom.getId());
            of.setStatus(0);
            orderFromService.updateById(of);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1);
        }
    }


    //---------------------------- property -------------------------------

    @Resource
    private OrderFromService orderFromService;

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private ShopEventService shopEventService;

    @Resource
    private ReceiptAddressService receiptAddressService;

    @Resource
    private ThinksService thinksService;

    @Resource
    private ShopService shopService;

    @Resource
    private UserService userService;

}
